package com.woniu.service.task;
/*
    @Title:
    @Author:Lingger
    @Description:
*/

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.woniu.pojo.User;
import com.woniu.pojo.Vip;
import com.woniu.service.IUserService;
import com.woniu.service.IVipService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.List;

@Slf4j
@Component
public class DeleteExpiredVIPTask {

    @Autowired
    private IVipService vipService;

    @Autowired
    private IUserService userService;

    @Scheduled(cron = "0 * * * * ?")
    public void deleteExpiredVIP() {

        //用户vip到期，删除vip表中到期的数据
        Date now = new Date();
        QueryWrapper<Vip> queryWrapperVipByExpirationTime = new QueryWrapper<>();
        queryWrapperVipByExpirationTime.le("expiration_time", now);

        //查询出即将被删的vip，取出这些即将被删的vip的userId
        List<Vip> deletedList = vipService.list(queryWrapperVipByExpirationTime);

        //通过name修改user表中的vip状态 及vip表中的vip状态
        for (Vip deletedVip : deletedList) {
            //获取即将删除的vip的name
            String name = deletedVip.getName();

            //修改user表中的vip状态
            QueryWrapper<User> queryWrapperUserByName = new QueryWrapper<>();
            queryWrapperUserByName.eq("name",name);
            User oneUser = userService.getOne(queryWrapperUserByName);

            if (oneUser.getVip() == 1){
                oneUser.setVip(0);

                //执行修改user表中数据
                userService.updateOne(oneUser);
            }

            //修改vip表中的vip状态
            QueryWrapper<Vip> queryWrapperVipByName = new QueryWrapper<>();
            queryWrapperVipByName.eq("name",name);
            Vip oneVip = vipService.getOne(queryWrapperVipByName);
            if (deletedVip.getStatus() == 1){
                oneVip.setStatus(0);

                //执行修改vip表中数据
                vipService.updateById(oneVip);
            }

        }
    }
}
